/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.rpc.api.support;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.reflect.TypeUtils;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.GenericArrayType;

/**
 * * 自定义类型
 * * <p>
 * * 用于描述泛型RPC接口返回值
 *
 * @author Leon Huo
 */
public class Type<T> {

    private JavaType javaType;
    private ParameterizedType parameterizedType;

    private Class<T> rawType;

    private static ObjectMapper objectMapper = new ObjectMapper();

    private Type(JavaType javaType, Class rawType) {
        this.javaType = javaType;
        this.rawType = rawType;
    }

    public Type(Class<T> rawClass, java.lang.reflect.Type... genericClasses) {
        this.rawType = rawClass;
        if (genericClasses.length == 0) {
            if (rawClass == null) {
                this.javaType = objectMapper.constructType(void.class);
            } else {
                this.javaType = objectMapper.constructType(rawClass);
            }
        } else {
            ParameterizedType parameterizedType = TypeUtils.parameterize(rawClass, genericClasses);
            this.parameterizedType = parameterizedType;
            this.javaType = objectMapper.constructType(parameterizedType);
        }
    }

    public static Type fromReflect(java.lang.reflect.Type type) {
        java.lang.reflect.Type tempType = type;
        while (!(tempType instanceof Class)) {
            if (tempType instanceof ParameterizedType) {
                tempType = ((ParameterizedType) tempType).getRawType();
            } else if (tempType instanceof GenericArrayType) {
                tempType = ((GenericArrayType) tempType).getGenericComponentType();
            } else {
                throw new RuntimeException("unsupport Type: " + tempType.getTypeName());
            }
        }

        Class rawType = (Class) tempType;
        return new Type(objectMapper.constructType(type), rawType);
    }

    public JavaType getJavaType() {
        return javaType;
    }

    public Class<T> getRawType() {
        return rawType;
    }

    public ParameterizedType getParameterizedType() {
        return parameterizedType;
    }
}
